﻿Imports SIGI.Common.BE
Imports SIGI.Common

Public Class frmABMProfiles

#Region "<< -Attributes- >>"
    Private _ProfileList As List(Of ProfileBE) = Nothing
    Private _ScreenList As List(Of ScreenBE) = Nothing
    Private _PermissionList As List(Of PermissionBE) = Nothing
#End Region

#Region "<< -Events- >>"

    Private Sub frmABMProfiles_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

        Try
            'Asigno el id de pantalla
            _Screen = Common.CommonDefinitions.Screen.ABMProfiles

            'Cargo los perfiles disponibles
            LoadProfiles()
            If _ProfileList.Count > 0 Then
                'Obtengo el listado de pantallas disponibles.
                LoadScreens()
                'Obtengo los permisos disponibles.
                LoadPermissions()
            End If

            'Asigno los eventos
            AddHandler btnNew.Click, AddressOf btnNew_Click
            AddHandler btnUpdate.Click, AddressOf btnUpdate_Click
            AddHandler btnDelete.Click, AddressOf btnDelete_Click
            AddHandler btnSave.Click, AddressOf btnSave_Click
            AddHandler btnCancel.Click, AddressOf btnCancel_Click
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub btnAddScreenPermission_Click(sender As System.Object, e As System.EventArgs) Handles btnAddScreenPermission.Click
        Dim wUC_ScreenPermission As UC_Screen_Permission = Nothing

        Try
            If lstPermissions.Items.Count = 0 Or lstScreen.Items.Count = 0 Then
                btnAddScreenPermission.Enabled = False
                Return
            End If

            If Not chkAllScreen.Checked Then
                'Compruebo que se haya seleccionado al menos un pantalla y el permiso a asignarle
                If lstScreen.SelectedItems.Count > 0 And lstPermissions.SelectedIndex <> -1 Then
                    For Each wScreen As ScreenBE In lstScreen.SelectedItems
                        wUC_ScreenPermission = New UC_Screen_Permission
                        wUC_ScreenPermission.Permission = DirectCast(lstPermissions.SelectedItem, PermissionBE)
                        wUC_ScreenPermission.Screen = DirectCast(wScreen, ScreenBE)

                        'Lo agrego a la lista de pantallas con permisos asignados
                        pnlPermissions.Controls.Add(wUC_ScreenPermission)
                        'Quito la pantalla de la lista de pantallas a asignar
                        _ScreenList.Remove(wScreen)
                    Next
                End If
            Else
                For Each wScreen As ScreenBE In lstScreen.Items
                    wUC_ScreenPermission = New UC_Screen_Permission
                    wUC_ScreenPermission.Permission = DirectCast(lstPermissions.SelectedItem, PermissionBE)
                    wUC_ScreenPermission.Screen = DirectCast(wScreen, ScreenBE)

                    'Lo agrego a la lista de pantallas con permisos asignados
                    pnlPermissions.Controls.Add(wUC_ScreenPermission)
                    'Quito la pantalla de la lista de pantallas a asignar
                    _ScreenList.Remove(wScreen)
                Next
            End If
            'Actualizo la vista de la lista de pantallas.
            BindingSource.ResetBindings(False)
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub btnUpdate_Click(sender As System.Object, e As System.EventArgs)
        ButtonsController(btnUpdate.Name)
    End Sub

    Private Sub btnNew_Click(sender As System.Object, e As System.EventArgs)
        'Por si habia realizado alguna busqueda reseteo a cero
        pnlPermissions.Controls.Clear()
        LoadScreens()
        ButtonsController(btnCancel.Name)
        'Ahora utilizo el comportamiento de nuevo
        ButtonsController(btnNew.Name)
        cmbProfiles.Visible = False
        txtProfileName.Visible = True
        txtProfileName.Focus()
        lblNecesary.Visible = True
    End Sub

    Private Sub btnDelete_Click(sender As System.Object, e As System.EventArgs)
        ButtonsController(btnDelete.Name)
        DeleteProfile()
    End Sub

    Private Sub btnSave_Click(sender As System.Object, e As System.EventArgs)
        Try
            If _Behavior = CommonDefinitions.CRUD.Insert Then
                InsertProfile()
                'Operación finalizo correctamente
                ButtonsController(btnSave.Name)
                'Limpio el textbox
                txtProfileName.Text = String.Empty
            End If

            If _Behavior = CommonDefinitions.CRUD.Update Then
                UpdateProfile()
                'Operación finalizo correctamente
                ButtonsController(btnSave.Name)
            End If
        Catch ex As Exception
            _MsgBox.ShowMessage("Perfil", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub btnCancel_Click(sender As System.Object, e As System.EventArgs)
        Try
            If _Behavior = CommonDefinitions.CRUD.Update Then
                'Recargo la lista de pantallas y limpio la de pantallas asignadas
                LoadScreens()
                pnlPermissions.Controls.Clear()
            End If
            ButtonsController(btnCancel.Name)
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub btnSearch_Click(sender As System.Object, e As System.EventArgs) Handles btnSearch.Click
        Dim wProfileScreenController As Profiles_ScreensController = Nothing
        Dim wScreenController As ScreenController = Nothing
        Dim wProfile_ScreenBE As Profile_ScreenBE = Nothing
        Dim wAssignedScreenList As List(Of Profile_ScreenBE) = Nothing
        Dim wUC_ScreenPermission As UC_Screen_Permission = Nothing
        Dim wIdScreen As Integer = 0
        Dim wIdPermission As Integer = 0
        Dim wIdx As Integer = 0

        Try
            'Limpio los resultados anteriores
            pnlPermissions.Controls.Clear()

            'Obtengo el listado de pantallas
            wScreenController = New ScreenController
            _ScreenList = wScreenController.Search()

            'Busco las pantallas asignadas según el perfil
            wProfileScreenController = New Profiles_ScreensController
            wProfile_ScreenBE = New Profile_ScreenBE
            wProfile_ScreenBE.IdProfile = cmbProfiles.SelectedValue
            wAssignedScreenList = wProfileScreenController.SearchByParams(wProfile_ScreenBE)

            'Cargo estas pantallas en el panel de asignadas.
            For Each wProfileScreen As Profile_ScreenBE In wAssignedScreenList
                wUC_ScreenPermission = New UC_Screen_Permission
                wIdScreen = wProfileScreen.IdScreen
                wIdPermission = wProfileScreen.IdPermission

                'Busco en la listado general de pantallas y permisos los que correspoden según el actual asignado.
                wUC_ScreenPermission.Screen = DirectCast(_ScreenList.Find(Function(x) x.Id = wIdScreen), ScreenBE)
                wUC_ScreenPermission.Permission = DirectCast(_PermissionList.Find(Function(x) x.Id = wIdPermission), PermissionBE)
                pnlPermissions.Controls.Add(wUC_ScreenPermission)
                wIdx = _ScreenList.FindIndex(Function(s) s.Id = wProfileScreen.IdScreen.Value)
                _ScreenList.RemoveAt(wIdx)
            Next

            '_ScreenList.Clear()
            BindingSource.DataSource = _ScreenList
            lstScreen.DataSource = BindingSource
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub

    Private Sub btnRemoveAsingned_Click(sender As System.Object, e As System.EventArgs) Handles btnRemoveAsingned.Click
        Dim wIdx As Integer = 0
        Dim wUC_Screen As UC_Screen_Permission = Nothing
        Try
            wIdx = pnlPermissions.Controls.Count - 1
            While wIdx >= 0
                wUC_Screen = DirectCast(pnlPermissions.Controls(wIdx), UC_Screen_Permission)
                If wUC_Screen.Selected Then
                    _ScreenList.Add(wUC_Screen.Screen)
                    pnlPermissions.Controls.Remove(wUC_Screen)
                End If

                wIdx -= 1
            End While

            'Actualizo la vista de lista de pantallas sin asignar
            BindingSource.ResetBindings(False)
        Catch ex As Exception
            _MsgBox.ShowMessage("Excepción", ex.Message, frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
        End Try
    End Sub
#End Region

#Region "<< -Methods- >>"
    Private Sub LoadScreens()
        Dim wScreenController As ScreenController = New ScreenController

        _ScreenList = wScreenController.Search()
        lstScreen.DisplayMember = "Description"
        lstScreen.ValueMember = "Id"
        BindingSource.DataSource = _ScreenList
        lstScreen.DataSource = BindingSource

        BindingSource.ResetBindings(False)
    End Sub

    Private Sub LoadPermissions()
        Dim wPermissionController As PermissionController = New PermissionController

        _PermissionList = wPermissionController.Search()
        lstPermissions.DisplayMember = "Description"
        lstPermissions.ValueMember = "Id"
        lstPermissions.DataSource = _PermissionList
        lstPermissions.Refresh()
    End Sub

    Private Sub LoadProfiles()
        Dim wProfileController As ProfileController = New ProfileController

        _ProfileList = wProfileController.Search()
        cmbProfiles.DisplayMember = "Description"
        cmbProfiles.ValueMember = "Id"
        cmbProfiles.DataSource = _ProfileList

        If _ProfileList.Count = 0 Then
            btnNew.Enabled = False
            btnUpdate.Enabled = False
            btnDelete.Enabled = False
        Else
            cmbProfiles.SelectedIndex = 0
        End If
    End Sub

    Private Sub ButtonsController(pButton As String)
        Select Case pButton
            Case btnUpdate.Name
                If pnlPermissions.Controls.Count > 0 Then
                    btnAddScreenPermission.Enabled = True
                    btnSave.Enabled = True
                    btnCancel.Enabled = True
                    btnNew.Enabled = False
                    btnUpdate.Enabled = False
                    btnDelete.Enabled = False
                    btnRemoveAsingned.Enabled = True
                    _Behavior = CommonDefinitions.CRUD.Update
                Else
                    If lstPermissions.Items.Count = 0 Or lstScreen.Items.Count = 0 Then
                        _MsgBox.ShowMessage("Perfil", "No hay Pantallas o Permisos disponibles",
                                            frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
                        btnAddScreenPermission.Enabled = False
                    Else
                        _MsgBox.ShowMessage("Perfil", "Seleccione el Perfil a modificar y presione Buscar primero",
                                           frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
                        btnAddScreenPermission.Enabled = False
                    End If
                End If

            Case btnNew.Name
                If lstPermissions.Items.Count > 0 And lstScreen.Items.Count > 0 Then
                    btnAddScreenPermission.Enabled = True
                    btnSave.Enabled = True
                    btnCancel.Enabled = True
                    btnNew.Enabled = False
                    btnUpdate.Enabled = False
                    btnDelete.Enabled = False
                    btnSearch.Visible = False
                    btnRemoveAsingned.Enabled = True
                    _Behavior = CommonDefinitions.CRUD.Insert
                Else
                    _MsgBox.ShowMessage("Faltan Datos", "No hay Pantallas o Permisos disponibles",
                                        frmMessage.MessageType.Error_, frmMessage.MessageButtons.Ok)
                    btnAddScreenPermission.Enabled = False
                End If
            Case btnDelete.Name
                'btnSave.Enabled = True
                'btnCancel.Enabled = True
                'btnNew.Enabled = False
                'btnUpdate.Enabled = False
                'btnDelete.Enabled = False

                _Behavior = CommonDefinitions.CRUD.Delete

            Case btnSave.Name
                btnSave.Enabled = False
                btnCancel.Enabled = False
                btnNew.Enabled = True
                btnUpdate.Enabled = True
                btnDelete.Enabled = True

                _Behavior = CommonDefinitions.CRUD.Read

            Case btnCancel.Name
                btnSave.Enabled = False
                btnCancel.Enabled = False
                btnNew.Enabled = True
                btnUpdate.Enabled = True
                btnDelete.Enabled = True
                btnAddScreenPermission.Enabled = False
                btnSearch.Visible = True
                cmbProfiles.Visible = True
                txtProfileName.Visible = False
                lblNecesary.Visible = False

                _Behavior = CommonDefinitions.CRUD.Read
            Case Else
                'No hago nada
        End Select
    End Sub

    Private Sub InsertProfile()
        Dim wProfileController As ProfileController = Nothing
        Dim wProfileScreenList As List(Of Profile_ScreenBE) = Nothing
        Dim wProfileScreen As Profile_ScreenBE = Nothing

        If String.IsNullOrEmpty(txtProfileName.Text.Trim) Or lstScreen.Items.Count > 0 Then
            Throw New Exception("Debe completar los datos obligatorios")

            IIf(String.IsNullOrEmpty(txtProfileName.Text.Trim), txtProfileName.Focus(), lstScreen.Focus())
            Return
        End If

        wProfileScreenList = New List(Of Profile_ScreenBE)
        For Each wScreenPermission As UC_Screen_Permission In pnlPermissions.Controls
            wProfileScreen = New Profile_ScreenBE
            wProfileScreen.IdScreen = wScreenPermission.Screen.Id.Value
            wProfileScreen.IdPermission = wScreenPermission.Permission.Id.Value

            wProfileScreenList.Add(wProfileScreen)
        Next

        'Inserto el nuevo perfil
        wProfileController = New ProfileController
        wProfileController.Insert(txtProfileName.Text.Trim, wProfileScreenList)
        'Recargo la lista de perfiles.
        LoadProfiles()
        'Recargo las pantallas
        LoadScreens()
        'Limpio las pantallas asignadas
        pnlPermissions.Controls.Clear()
        'Reseteo a cero
        ButtonsController(btnCancel.Name)
        'Informo del éxito
        _MsgBox.ShowMessage("Perfil", "Los datos han sido guardados correctamente",
                                    frmMessage.MessageType.Information_, frmMessage.MessageButtons.Ok)
    End Sub

    Private Sub UpdateProfile()
        Dim wProfileController As ProfileController = Nothing
        Dim wProfileScreenList As List(Of Profile_ScreenBE) = Nothing
        Dim wProfileScreen As Profile_ScreenBE = Nothing

        If lstScreen.Items.Count > 0 Then
            Throw New Exception("Faltan Pantallas de asignar")
            Return
        End If

        wProfileScreenList = New List(Of Profile_ScreenBE)
        For Each wScreenPermission As UC_Screen_Permission In pnlPermissions.Controls
            wProfileScreen = New Profile_ScreenBE
            wProfileScreen.IdScreen = wScreenPermission.Screen.Id.Value
            wProfileScreen.IdPermission = wScreenPermission.Permission.Id.Value
            wProfileScreen.IdProfile = cmbProfiles.SelectedValue

            wProfileScreenList.Add(wProfileScreen)
        Next

        'Actualizo el Perfil
        wProfileController = New ProfileController
        wProfileController.Update(wProfileScreenList)

        'Recargo las pantallas
        LoadScreens()
        'Limpio las pantallas asignadas
        pnlPermissions.Controls.Clear()
        'Reseteo a cero
        ButtonsController(btnCancel.Name)
        'Informo del éxito
        _MsgBox.ShowMessage("Perfil", "Los datos han sido guardados correctamente",
                                    frmMessage.MessageType.Information_, frmMessage.MessageButtons.Ok)
    End Sub

    Private Sub DeleteProfile()
        Dim wOption As frmMessage.MsgResult
        Dim wProfileController As ProfileController = Nothing

        wOption = _MsgBox.ShowMessage("Perfil", "Desea eliminar el perfil",
                                      frmMessage.MessageType.Question_,
                                      frmMessage.MessageButtons.OkCancel)
        If wOption = frmMessage.MsgResult.Cancel Then Return

        'Elimino el perfil
        wProfileController = New ProfileController
        wProfileController.Delete(cmbProfiles.SelectedValue)
        _MsgBox.ShowMessage("Perfil", "El Perfil ha sido eliminado correctamente", frmMessage.MessageType.Information_, frmMessage.MessageButtons.Ok)
        'Actualizo la lista de Perfiles
        LoadProfiles()

        _Behavior = CommonDefinitions.CRUD.Read
    End Sub
#End Region

End Class
